package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.NoAuthorization;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 今日佳人service
 */
@Service
public class TodayBestService {

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    private final ObjectMapper  MAPPER = new ObjectMapper();

    /*@Autowired
    private UserService userService;*/

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String defaultRecommendUsers;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;
    /**
     * 查询今日佳人
     * @param   //token数据
     * @return
     */
    public TodayBest queryTodayBest() {
        //根据传入token查询当前的登录信息  判断用户是否存在再redis中
        /*User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return null;
        }*/

        //用工具类获取
        User user = UserThreadLocal.get();

        //传入用户id ，查询今日佳人
        TodayBest todayBest = this.recommendUserService.queryTodayBest(user.getId());
        // 如果最佳匹配为空，进行默认推荐
        if (null == todayBest) {
            // 默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
            todayBest.setFateValue(98L);
        }


        //补全信息  处理推荐出来的数据，访问数据库，补全其它数据
        UserInfo userInfo = this.userInfoService.queryById(todayBest.getId());
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        return todayBest;
    }

    /**
     * 首页推荐查询
     * @param queryParam
     * @param
     * @return
     */
    public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam) {
        //根据传入token判断用户是否存在
        /*User user = userService.queryUserByToken(token);
        if(null == user){
            return null;
        }*/
        //用工具类获取
        User user = UserThreadLocal.get();
        // 用户存在，根据用户id查询存在的集合
        PageResult pageResult = new PageResult();
        // 调用interface分页查询
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(),
                queryParam.getPage(),queryParam.getPagesize()
                );
        // 如果推荐表中为空，则需要默认表数据
        List<RecommendUser> records = pageInfo.getRecords();
        if(CollectionUtils.isEmpty(pageInfo.getRecords())){
            // 默认推荐列表
            String[] recommendUserIds = StringUtils.split(defaultRecommendUsers, ",");
            for (String recommendUserId : recommendUserIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(recommendUserId));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70,98));
                records.add(recommendUser);
            }
        }
        pageResult.setCounts(0);//前端不计算，仅需要返回的字段
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());

        // 拿到基础信息进行进一步查询
        //List<RecommendUser> records = pageInfo.getRecords();  //查询获得所有推荐对象

        // 存放得到的推荐集合用户id
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : records) {
            userIds.add(record.getUserId());
        }
        // 查询条件对象
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        // 性别条件比较
        if (StringUtils.isNotEmpty(queryParam.getGender())) { //性别条件
            if (queryParam.getGender().equals("man")) {
                //queryWrapper.eq("sex", 1);
            } else {
                //queryWrapper.eq("sex", 2);
            }
        }

        // 居住城市比较
        if (StringUtils.isNotEmpty(queryParam.getCity())) { //居住城市
            //queryWrapper.eq("city", queryParam.getCity());
        }
        //年龄比较
        if (queryParam.getAge() != null) { //年龄
            //queryWrapper.lt("age", queryParam.getAge());
        }

        //调用service查询
        List<UserInfo> userInfos = this.userInfoService.queryList(queryWrapper);
        //今日最佳创建集合
        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            //设置缘分值
            for (RecommendUser record : records) {
                if(userInfo.getUserId().longValue() == record.getUserId().longValue()){
                    double score = Math.floor(record.getScore());
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            // 结果加入集合
            todayBests.add(todayBest);
        }
        //排序集合，按照score倒序排序
        Collections.sort(todayBests, (o1, o2) -> new Long(o2.getFateValue() - o1.getFateValue()).intValue());

        // 加入返回到前台的对象中
        pageResult.setItems(todayBests);
        return pageResult;
    }

    /**
     * 查询今日佳人详细信息
     * @param userId
     * @return
     */

    public TodayBest queryTodayBest(Long userId) {

        User user = UserThreadLocal.get();

        TodayBest todayBest = new TodayBest();
        //补全信息
        UserInfo userInfo = this.userInfoService.queryById(userId);
        todayBest.setId(userId);
        todayBest.setAge(userInfo.getAge());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));

        double score = this.recommendUserService.queryScore(userId, user.getId());
        if(score == 0){
            score = 98; //默认分值
        }

        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }

    @Autowired
    private QuestionService questionService;
    /**
     * 查询陌生人问题
     * @param userId
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = this.questionService.queryQuestion(userId);
        if(null != question){
            return question.getTxt();
        }
        return "";
    }



    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        User user = UserThreadLocal.get();
        UserInfo userInfo = this.userInfoService.queryById(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", this.queryQuestion(userId));
        msg.put("strangerQuestion", userInfo.getNickName());
        msg.put("reply", reply);

        try {
            String msgStr = MAPPER.writeValueAsString(msg);

            String targetUrl = this.ssoUrl + "/user/huanxin/messages";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);

            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(params, headers);

            ResponseEntity<Void> responseEntity = this.restTemplate.postForEntity(targetUrl, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (Exception e) {
            e.printStackTrace();
        }


        return false;
    }


    /**
     * 搜附近好友
     * @param gender
     * @param distance
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        User user = UserThreadLocal.get();
        // 查询当前用户的位置信息
        UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();
        Double latitude = userLocationVo.getLatitude();

        // 根据当前用户的位置信息查询附近的好友
        List<UserLocationVo> userLocationList = this.userLocationApi
                .queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));

        if (CollectionUtils.isEmpty(userLocationList)) {
            return Collections.emptyList();
        }

        // 获取所有附近好友ids
        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationList) {
            userIds.add(locationVo.getUserId());
        }

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.in("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.in("sex", SexEnum.WOMAN);
        }
        // 查询数据库
        List<UserInfo> userInfoList = this.userInfoService.queryList(queryWrapper);

        List<NearUserVo> nearUserVoList = new ArrayList<>();

        for (UserLocationVo locationVo : userLocationList) {

            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                // 排除自己
                continue;
            }

            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();

                    nearUserVo.setUserId(userInfo.getUserId());
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());

                    nearUserVoList.add(nearUserVo);
                    break;
                }
            }
        }

        return nearUserVoList;
    }

    /**
     * 探花功能
     * @return
     */
    public List<TodayBest> queryCardsList() {
        // 获取当前用户
        User user = UserThreadLocal.get();
        // 查询推荐出来的50个
        PageInfo<RecommendUser> pageInfo = this.recommendUserService.queryRecommendUserList(user.getId(), 1, 50);
        List<RecommendUser> records = pageInfo.getRecords();
        // 如果为空，则使用推荐数据
        if(CollectionUtils.isEmpty(records)){
            String[] recommendUserIds = StringUtils.split(defaultRecommendUsers,",");
            for (String recommendUserId : recommendUserIds) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(recommendUserId));
                recommendUser.setToUserId(user.getId());
                //recommendUser.setScore(RandomUtils.nextDouble(70,98));
                records.add(recommendUser);
            }
        }

        List<RecommendUser> newRecords = new ArrayList<>();
        //默认推荐10个所以要先判断
        if(10 < records.size()){
            for (int i = 0; i < 10; i++) {
                createRecommendUser(records,newRecords);
            }
        }

        // 循环获得的数据，查询所得的推荐用户id
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            userIds.add(record.getUserId());
        }

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id",userIds);
        List<UserInfo> userInfos = this.userInfoService.queryList(queryWrapper);


        List<TodayBest> todayBests = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            TodayBest todayBest = new TodayBest();
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
            todayBest.setFateValue(0L);

            todayBests.add(todayBest);
        }
        return todayBests;
    }

    /**
     * 递归去除重复
     * @param records
     * @param newRecords
     */
    private void createRecommendUser(List<RecommendUser> records,List<RecommendUser> newRecords){
        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0,records.size()-1));
        if(newRecords.size() ==0 || !newRecords.contains(recommendUser)){
            newRecords.add(recommendUser);
        }else {
            createRecommendUser(records,newRecords);
        }
    }


    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;
    /**
     *   探花-喜欢
     * @param likeUserId
     * @return
     */
    public Boolean likeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        String id = this.userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(id)) {
            return false;
        }

        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }
        return true;
    }

    /**
     * 探花-不喜欢
     * @param likeUserId
     * @return
     */
    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }
}
